# -*- coding: UTF-8 -*-
""" Shows the results of previous game

    From GameState It needs a pair of players and list of words they guessed.
    It also needs current_word if it was time-outed, or None
    It can change phase to the screen "from -> to"
    furthermore, here player can delete words, if pair failed it,
    but clicked, that they guessed it
"""

import os
from kivy.clock import Clock
from kivy.core.audio import SoundLoader

from ui.fittable_widgets import FittableButton, FittableLabel
from kivy.properties import StringProperty
from kivy.properties import NumericProperty
from kivy.uix.popup import Popup
from model.gamestate import *
from model.gamestate import Phase
from ui.hat_widget import HatWidget
from kivy.clock import Clock
from ui.hat_widget import open_ok_popup
from kivy.uix.boxlayout import BoxLayout
from model.explanatory_dictionary import ExplanatoryDictionary
from ui.scroll_popup import ScrollPopup, open_scroll_popup
from kivy.uix.image import Image


class HelpButton(FittableButton):
    def __init__(self, text, root, **kwargs):
        self.root = root
        self.word_text = text
        super(HelpButton, self).__init__(**kwargs)

    def get_help(self):
        if self.word_text.lower() in self.root.presenter.\
           explanatory_dictionary.dictionary:
            open_scroll_popup(self.word_text.lower(),
                              self.root.presenter.explanatory_dictionary.
                              dictionary[self.word_text.lower()],
                              self.root)
        else:
            open_ok_popup(self.word_text, u'No information', self.root)


class WordLabel(FittableButton):
    colors = {WordGuessResult.FAIL: 'red',
              WordGuessResult.GUESS: 'green',
              WordGuessResult.TIME_OUT: 'default',
              WordGuessResult.PUT_BACK: 'default'}
    ORDER = [WordGuessResult.GUESS,
             WordGuessResult.FAIL,
             WordGuessResult.PUT_BACK]

    def __init__(self, guess_result, root, **kwargs):
        self.guess_result = guess_result
        self.word = guess_result
        self.root = root
        super(WordLabel, self).__init__(**kwargs)

    #def on_touch_up(self, touch):
        #if self.collide_point(touch.x, touch.y):
            #self.swap_result()

    def swap_result(self):
        word = self.guess_result
        order = self.ORDER
        if word.result == WordGuessResult.TIME_OUT:
            word.result = WordGuessResult.PUT_BACK
        word.result = order[(order.index(word.result) + 1) % len(order)]

        self.color_name = self.colors[word.result]
        self.texture_update()
        self.root.update()


class ResultsOfOnePair(HatWidget):
    next_phase = NumericProperty()

    def __init__(self, gamestate, presenter, **kwargs):
        """ Sets up the screen.
        """
        self.button_text = {Phase.GAME_RESULTS: _('Game results'),
                            Phase.FROM_TO: _('Pass the hat')}

        self.words_left = len(gamestate.hat.words)

        self.next_phase = Phase.FROM_TO

        super(ResultsOfOnePair, self).__init__(**kwargs)
        self.presenter = presenter
        self.gamestate = gamestate

        self.gamestate.players.players_select_strategy.is_same_pair = False
        self.gamestate.game_round.is_replayed = False

        self.word_list.bind(minimum_height=self.word_list.setter('height'))

        for word in self.gamestate.game_round.words:
            if (word.result in [WordGuessResult.FAIL, WordGuessResult.GUESS,
                                WordGuessResult.TIME_OUT]):
                box_layout = BoxLayout(orientation='horizontal',
                                       size_hint=(1, None), height='35sp')
                box_layout.add_widget(WordLabel(word, self))
                box_layout.add_widget(HelpButton(word.word.text, self))
                self.word_list.add_widget(box_layout)

        if self.presenter.settings.game.pony_enabled:
            pony_size = self.width
            pony_path = os.path.join(os.path.dirname(__file__),
                                     '..', 'assets', 'pony.png')
            pony = Image(source=pony_path, size=(pony_size, pony_size), size_hint=(None, None))
            self.add_widget(pony, index=1)
        self.update()

    def to_next(self, is_finishing=False):
        """ changes phase to 'FROM_TO' or 'GAME_RESULTS'
        called on 'Next Round' button release
        """
        is_replayed = self.gamestate.game_round.is_replayed
        if not is_replayed:
            for guess in self.gamestate.game_round.words[:]:
                if guess.result in [WordGuessResult.PUT_BACK,
                                    WordGuessResult.TIME_OUT]:
                    self.gamestate.hat.add_word(guess.word)

        if self.gamestate.rounds is None:
            self.gamestate.rounds = []
        self.gamestate.rounds.append(self.gamestate.game_round)
        self.gamestate.game_round = None
        self.okbutton.enabled = False
        if is_finishing:
            self.presenter.change_phase(Phase.CURRES)
        else:
            self.presenter.change_phase(self.next_phase)

    def replay_round(self):
        self.gamestate.players.players_select_strategy.is_same_pair = True
        self.gamestate.game_round.is_replayed = True
        self.to_next()

    def update(self):
        self.update_replay_button()
        self.update_next_phase()

    def update_next_phase(self):
        self.next_phase = Phase.FROM_TO
        words_in_hat = len(self.gamestate.hat.words)
        for guess in self.gamestate.game_round.words:
            if guess.result in [WordGuessResult.PUT_BACK,
                                WordGuessResult.TIME_OUT]:
                words_in_hat += 1
        self.max_round_num = self.gamestate.settings.max_round_num
        self.round_num = int((len(self.gamestate.rounds) + 1) /
                             len(self.gamestate.players.players)) + 1
        if (words_in_hat == 0) \
           or ((self.max_round_num is not None)
               and (self.round_num > self.max_round_num)):
            self.next_phase = Phase.GAME_RESULTS
        else:
            self.next_phase = Phase.FROM_TO

    def update_replay_button(self):
        can_replay = self.presenter.settings.game.may_replay_round and \
            len(self.gamestate.hat.words) > 0
